const redis = require('redis');
const fs = require('fs');
const path = require('path');

// 创建单例 Redis 客户端
let client = null;

// 初始化 Redis 客户端的函数
const initRedisClient = async () => {
  if (!client) {
    client = redis.createClient({
      host: 'localhost',
      port: 6379,
      retry_strategy: function(options) {
        if (options.error && options.error.code === 'ECONNREFUSED') {
          return new Error('Redis服务器拒绝连接');
        }
        if (options.total_retry_time > 1000 * 60 * 60) {
          return new Error('重试时间已超过');
        }
        if (options.attempt > 10) {
          return undefined;
        }
        return Math.min(options.attempt * 100, 3000);
      }
    });

    // Redis 错误处理
    client.on('error', (err) => {
      console.error('Redis 错误:', err);
    });

    // 连接 Redis
    await client.connect();
  }
  return client;
};

// 获取省市县乡村数据
const getAddressItems = async (ctx, next) => {
  try {
    // 确保 Redis 客户端已初始化
    const redisClient = await initRedisClient();
    const body = ctx.query.codes;

    // 获取省份数据
    if (!body) {
      const data = await redisClient.get('province');
      if (data) {
        ctx.body = { 
          code: 200, 
          data: JSON.parse(data), 
          msg: '成功' 
        };
      } else {
        const filePath = path.join(__dirname, '../../pubilc/address/province.json');
        const fileContent = fs.readFileSync(filePath, 'utf8');
        await redisClient.set('province', fileContent);
        ctx.body = { 
          code: 200, 
          data: JSON.parse(fileContent), 
          msg: '成功' 
        };
      }
      return;
    }

    // 处理地址查询
    if (body && body.split(',').length) {
      const provinceData = await redisClient.get('province');
      const codes = body.split(',');
      const province = JSON.parse(provinceData).find(item => item.code == codes[0]);

      if (!province) {
        throw new Error('省份数据不存在');
      }

      let cacheData = await redisClient.get(province.code);
      if (!cacheData) {
        const filePath = path.join(__dirname, `../../pubilc/address/${province.name}.json`);
        const fileContent = fs.readFileSync(filePath, 'utf8');
        const redisData = JSON.parse(fileContent).children;
        await redisClient.set(province.code, JSON.stringify(redisData));
        cacheData = JSON.stringify(redisData);
      }

      // 递归查找数据
      const result = [];
      let currentIndex = 0;

      const findChildren = (data) => {
        const parsedData = JSON.parse(data);
        if (codes[currentIndex + 1]) {
          currentIndex++;
          const target = parsedData.find(item => item.code == codes[currentIndex]);
          if (target && target.children) {
            findChildren(JSON.stringify(target.children));
          }
        } else {
          parsedData.forEach(item => {
            result.push({
              name: item.name,
              code: item.code
            });
          });
        }
      };

      findChildren(cacheData);

      ctx.body = {
        code: 200,
        data: result,
        msg: '成功'
      };
    }

  } catch (error) {
    console.error('处理地址数据错误:', error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      msg: '获取地址数据失败',
      error: error.message
    };
  }
};

// 优雅关闭函数
const gracefulShutdown = async () => {
  if (client) {
    try {
      await client.quit();
      client = null;
    } catch (err) {
      console.error('关闭 Redis 连接错误:', err);
    }
  }
};

process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

module.exports = {
  getAddressItems
};